package com.zhongmai.yzfgrabanorder.base;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.PermissionChecker;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.zhongmai.yzfgrabanorder.R;
import com.zhongmai.yzfgrabanorder.activity.MainActivity;
import com.zhongmai.yzfgrabanorder.utils.AppActivityManagerUtils;
import com.zhongmai.yzfgrabanorder.utils.LogUtils;

import java.lang.reflect.Field;

import butterknife.ButterKnife;


/**
 * 项目名称：Cniao5Store
 * 类描述：Activity基类
 * 创建人：Administrator
 * 创建时间：2017/10/25 0025 上午 9:52
 * 修改人：Administrator
 * 修改时间：2017/10/25 0025 上午 9:52
 * 修改备注：
 */

public abstract class BaseActivity extends AppCompatActivity {


    protected ViewGroup mRL_bar_layout;
    protected boolean isQuit = true;//是否双击退出

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//强制竖屏
        AppActivityManagerUtils.getInstance().addActivity(this);//添加Activity到栈中统一管理
        //当系统版本为4.4或者4.4以上时可以使用沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        /*加载布局文件*/
        initLayout();
        ButterKnife.bind(this);
        initView();
        initPermission();
    }

    /**
     * 设置沉浸式状态栏
     */
    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mRL_bar_layout = findViewById(R.id.mRL_bar_layout);
            final int statusHeight = getStatusBarHeight(this);
            mRL_bar_layout.post(new Runnable() {
                @Override
                public void run() {
                    int titleHeight = mRL_bar_layout.getHeight();
                    android.widget.RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams)
                            mRL_bar_layout.getLayoutParams();
                    params.height = statusHeight + titleHeight;
                    mRL_bar_layout.setLayoutParams(params);
                }
            });
        }
    }


    /**
     * 获取状态栏的高度
     *
     * @return
     */
    public static int getStatusBarHeight(AppCompatActivity appCompatActivity) {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return appCompatActivity.getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 添加Activity转场动画
     *
     * @param intent
     */
    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.anim_slide_in_right, R.anim.anim_slide_out_left);
    }

    /**
     * 添加Activity转场动画
     *
     * @param intent
     * @param requestCode
     */
    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.anim_slide_in_right, R.anim.anim_slide_out_left);
    }

    protected void openActivity(Class clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
    }

    /**
     * 添加退出Activity转场动画
     */
    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.anim_slide_in_left, R.anim.anim_slide_out_right);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppActivityManagerUtils.getInstance().removeActivity(this);//关闭时移除Activity
    }

    protected abstract void initLayout();

    protected abstract void initView();

    protected void initData() { }

    /**
     * 6.0以后请求SD卡权限
     */
    private void initPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            /*判定是否有读取SD卡权限*/
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
                    PermissionChecker.PERMISSION_GRANTED) {
                initData();
            } else {
                showToast("无储存权限");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 0) {
            if (grantResults[0] == PermissionChecker.PERMISSION_GRANTED) {
                LogUtils.showToastShort("授权SD卡成功");
                initData();
            } else {
                LogUtils.showToastShort("没有授权SD卡，可能会影响应用的使用");
            }
        }
    }


    public void showToast(String mag) {
        LogUtils.showToast(mag);
    }

    protected void logMag(String msg) {
        LogUtils.bugMes(msg, 6);
    }


    /**
     * 双击退出
     *
     * @param keyCode
     * @param event
     * @return
     */
    //记录用户首次点击返回键的时间
    private long firstTime = 0;

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (isQuit) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) {
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    firstTime = secondTime;
                    return true;
                } else {
                    finish();
                }
            }
        }
        return super.onKeyUp(keyCode, event);
    }
}
